import { useEffect, useState, useCallback } from 'react'
import { View, ScrollView } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { IHeaderBox, IUserItem, IloadMore, ISwitch } from '@/components/index'
import { SearchBar, Empty } from '@nutui/nutui-react-taro'
import { classAdminList, gradeList } from '@/axios/school'
import './index.scss'

interface InfoMgtProps {}

interface FormDataProps {
  pageNum: number
  pageSize: number
  gradeCode?: number
  userName?: string
}

const InfoMgtIndex: React.FC<InfoMgtProps> = () => {
  const [listData, setListData] = useState<API.ClassAdminItem[]>([])
  const [triggered, setTriggered] = useState<boolean>(false)
  const [gradeData, setGradeData] = useState<API.GradeItem[]>([])
  const [times, setTimes] = useState<any>(null)

  const [formData, setFormData] = useState<FormDataProps>({
    pageNum: 1,
    pageSize: 10,
    gradeCode: 0,
    userName: ''
  })

  const [loadStatus, setLoadStatus] = useState<API.LoadStatusProps>('more')

  const [otherInfo, setOtherInfo] = useState<
    Pick<API.TableResProps<null>, 'pages'>
  >({
    pages: 1
  })

  const getListData = useCallback(async () => {
    try {
      if (formData.pageNum > 1) setLoadStatus('loading')
      const params = {
        ...formData
      }
      if (params.gradeCode == 0) delete params.gradeCode
      if (params.userName == '') delete params.userName
      const { list = [], ...other } = await classAdminList(params)
      if (formData.pageNum == 1) {
        setListData(list)
      } else {
        setListData(preState => [...preState, ...list])
      }
      setLoadStatus(other.pages > formData.pageNum ? 'more' : 'noMore')
      setOtherInfo(other)
      setTriggered(false)
    } catch {}
  }, [formData])

  const getGradeList = async () => {
    try {
      const results = await gradeList()
      setGradeData(results || [])
    } catch {}
  }

  useEffect(() => {
    getGradeList()
  }, [])

  useEffect(() => {
    getListData()
  }, [getListData])

  useDidShow(() => {
    Taro.hideHomeButton()
  })

  const onRefresh = () => {
    setTriggered(true)
    setFormData({
      pageNum: 1,
      pageSize: 10,
      userName: '',
      gradeCode: 0
    })
  }

  const handlerBottom = () => {
    if (otherInfo.pages == formData.pageNum) {
      setLoadStatus('noMore')
    } else {
      setFormData({
        ...formData,
        pageNum: formData.pageNum + 1
      })
      setLoadStatus('loading')
    }
  }

  const onChangeSearch = (value: string) => {
    if (times) {
      clearTimeout(times)
      setTimes(null)
    }
    const time1 = setTimeout(() => {
      setFormData({
        pageNum: 1,
        pageSize: 10,
        userName: value
      })
    }, 1500)
    setTimes(time1)
  }

  const handleClickUser = (record: API.ClassAdminItem) => {
    // Taro.setStorageSync("ISADMIN", true);
    Taro.setStorageSync('CLASSRES', record)
    Taro.navigateTo({
      url: '/pages/classMgt/infoMgt/index'
    })
  }

  return (
    <View className='info_page'>
      <View className='search_box'>
        <SearchBar placeholder='请输入老师信息' onChange={onChangeSearch} />
      </View>
      <ScrollView
        scrollY
        className='scrollview'
        onRefresherRefresh={onRefresh}
        enableBackToTop
        refresherEnabled
        refresherBackground='#f8f8fb'
        refresherTriggered={triggered}
        scrollWithAnimation
        onScrollToLower={handlerBottom}
      >
        <View className='card_box'>
          <ISwitch
            options={gradeData}
            current={formData.gradeCode as number}
            onChange={(value: number) =>
              setFormData({
                pageNum: 1,
                pageSize: 10,
                gradeCode: value,
                userName: ''
              })
            }
          />
          <View className='list_box'>
            <IHeaderBox
              title={
                formData.gradeCode == 0
                  ? '全部'
                  : (gradeData.find(
                      item => item.gradeCode == formData.gradeCode
                    )?.gradeName as string)
              }
            />
            <View className='data_info'>
              {listData.length > 0 ? (
                <>
                  {listData.map((item: API.ClassAdminItem) => (
                    <IUserItem
                      key={item.userName}
                      sourceData={item}
                      handleClick={() => handleClickUser(item)}
                    />
                  ))}
                  <IloadMore loadStatus={loadStatus} />
                </>
              ) : (
                <Empty imageSize={120} />
              )}
            </View>
          </View>
        </View>
      </ScrollView>
    </View>
  )
}

export default InfoMgtIndex
